<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片部分 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        :closable="false"
        type="info"
        center
        show-icon
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :active="activeindex - 0"
        process-status="success"
        finish-status="success"
        align-center
        space="20%"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs侧边区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-tabs
          :before-leave="beforeLeaver"
          v-model="activeindex"
          @tab-click="tabsClick"
          :tab-position="'left'"
          style="100%"
        >
          <el-tab-pane label="商品信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyparams"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              label-width="150px"
              :label="item.attr_name"
              v-for="item in onlyparams"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :on-success="uploadSuccess"
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersobj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button class="addbtn" @click="add" type="primary">
              添加商品
            </el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="picVisible" width="50%">
      <img class="pic" :src="picPreview" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'Addgoods',
  created() {
    this.getCateList()
  },
  data() {
    return {
      // tabs与步骤条双向绑定的数据和当前激活的数据
      activeindex: '0',
      // 表单添加的数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 所选商品分类id的数组
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []

      },
      // 表单规则
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }]
      },
      // 商品分类数据
      cateList: [],
      // 联级选择器配置
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      // 动态参数
      manyparams: [],
      // 静态属性
      onlyparams: []
      ,
      // 图片上传的请求头
      headersobj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览框弹出
      picVisible: false,
      // 预览图片的url
      picPreview: ''
    }
  },
  methods: {
    getCateList() {
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/categories`)
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.cateList = response.data.data;
          }
        }).catch((error) => console.log(error))

    },
    // 联级选择器数据发生变化时调用
    handleChange() {
      console.log(this.addForm.goods_cat[2]);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 当tab之前切换时调用
    beforeLeaver(activetab, oldactivetab) {
      if (oldactivetab === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.info('请选择商品分类!')
        return false
      }

    },
    // 点击tabs时调用
    tabsClick() {
      if (this.activeindex === '1') {
        this.$http.get(`http://127.0.0.1:8888/api/private/v1/categories/${this.addForm.goods_cat[2]}/attributes`,
          { params: { sel: 'many' } })
          .then((response) => {
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              response.data.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
              });
              this.manyparams = response.data.data
              console.log(this.manyparams);
            }
          }).catch((error) => console.log(error))

      }
      if (this.activeindex === '2') {
        this.$http.get(`http://127.0.0.1:8888/api/private/v1/categories/${this.addForm.goods_cat[2]}/attributes`,
          { params: { sel: 'only' } })
          .then((response) => {
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              this.onlyparams = response.data.data
              console.log(this.onlyparams);
            }
          }).catch((error) => console.log(error))

      }
    },
    // 图片预览时调用
    handlePreview(file) {
      this.picPreview = file.response.data.url
      this.picVisible = true
    },
    // 移除图片时调用
    handleRemove(file) {
      const filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(i, 1)
    },
    // 图片上传成功时调用
    uploadSuccess(response) {
      const picobj = { pic: response.data.tmp_path }
      this.addForm.pics.push(picobj)
      console.log(this.addForm);

    },
    // 上传数据
    add() {
      console.log(this.addForm);
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          // 将goods_cat用深拷贝转换为字符串
          const form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cat.join(',')
          // 处理动态参数
          this.manyparams.forEach(item => {
            const info = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(info)
          })
          // 处理静态属性
          this.onlyparams.forEach(item => {
            const info = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(info)
          })
          form.attrs = this.addForm.attrs
          this.$http.post(`http://127.0.0.1:8888/api/private/v1/goods`,
            form)
            .then((response) => {
              if (response.data.meta.status !== 201) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success(response.data.meta.msg);
                this.$router.push('/goods')
              }
            }).catch((error) => console.log(error))
          console.log(form);
        } else {
          this.$message.error('请填入完整的表单内容!!')
        }

      })
    }
  }

}
</script>

<style scoped>
.el-steps {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 30px;
}
.pic {
  width: 100%;
  height: 100%;
}
.addbtn {
  margin-top: 20px;
}
</style>
<style>
.el-step__title.is-wait {
  font-size: 13px;
}

.el-checkbox {
  margin: 10px !important;
}
.ql-container {
  min-height: 200px;
}
</style>